<?php

namespace app\index\controller;

use app\common\model\UserModel;
use app\common\model\Users;
use think\Controller;
use think\Exception;
use think\facade\Session;
use think\Request;
//使用命令创建的控制器【php think make:controller index/Test】默认创建的是资源控制器
//创建普通的控制器php think make:controller index/Test --plain】
//
//一个资源控制器
class User extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //模板方法
        //return view();//  view方法不传参数，表示模板文件是【该模块/view/该控制器名/该方法名.html】
        //如果出现mkdir权限不够，先给目录755，还不行的话检查centos的selinux是否关闭了
        $data['users'] = UserModel::select();//获取表中全部的记录
        //$data['users'] = Users::where('nick','like','%Pi%')
          //  ->where('name','=','顽皮狗')
            //->select();//拼接条件查询数据
        return view('',$data);
    }


    public function data_list(Request $request){
        $params = $request->param();
        $search = $params['search'];
        $sort = $params['sort'];
        $order = $params['order'];
        $offset = $params['offset'];
        $limit = $params['limit'];

        //拼接查询语句
        $model = UserModel::where('1','=','1');

        if($search !== ''){
            $model = $model->where('name|nick|address','like',"%$search%");
        }

        $model = $model->order($sort,$order);
        $model = $model->limit($offset,$limit);

        $data['rows'] = $model->select();
        $data['total'] = $model->count();

        $data['search'] = $search;
        $data['sort'] = $sort;
        $data['order'] = $order;
        $data['offset'] = $offset;
        $data['limit'] = $limit;
        return json($data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $user = new UserModel([
            'name' => 'Test',
            'nick' => 'test',
            'password' => md5('Test'),
            'address' => '哈哈国呵呵省嘿嘿市哦哦县'
        ]);
        $user ->save();
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $user = Users::get($id);
        return json($user);
    }

    /**
     *
     *  显示编辑资源表单页及处理更新.
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit(Request $request)
    {
        if(!$request->isAjax()){
            $id = Session::get('userid');
            if(!$id){
                return redirect(url('index/user/login'));
            }
            $user = UserModel::where('id','=',$id)->find();
            $data['user'] = $user;
            return view('',$data);
        }else{
            $id = $request->param('id');
            $data['status'] = 0;
            $data['msg'] = 'error';
            $data['id'] = $id;
            $user = UserModel::where('id','=',$id)->find();
            if(!$user){
                $data['status'] = 0;
                $data['msg'] = '登录用户不存在或已被删除';
                $data['id'] = $id;
            }else{
                try{
                    $user['nick'] = $request->param('nick');
                    $user['address'] = $request->param('address');
                    $pw = trim($request->password);
                    if($pw !== ''){
                        $user['password'] = $pw;
                    }
                    $user['update_time'] = date('Y-m-d H:i:s',time());
                    $user->save();
                    $data['status'] = 1;
                    $data['msg'] = '修改成功！';
                    $data['user'] = $user;
                    Session::set('user',$user);
                    Session::set('username',$user['name']);
                    Session::set('nickname',$user['nick']);
                    Session::set('userid',$user['id']);
                }catch (\Exception $e){
                    $data['exception'] = $e;
                }
            }
            return json($data);
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    public function login(Request $request){
        if (!$request->isAjax()){
            return view();
        }else{
            $data['status'] = 0;
            $data['user'] = null;
            $data['msg'] = '用户名或密码错误';

            $post = $request->post();
            $user = UserModel::where('name','=',$post['name'])->where('password','=',md5($post['password']))->limit(0,1)->find();

            if($user){
                $data['status'] = 1;
                $data['user'] = $user;
                $data['msg'] = '登陆成功！！！';
                Session::set('user',$user);
                Session::set('username',$user['name']);
                Session::set('nickname',$user['nick']);
                Session::set('userid',$user['id']);
            }
            return json($data);
        }
    }

    public function logout(){
        Session::clear();
        return redirect('/index/user');
    }

    public function register(Request $request){
        if(!$request->isAjax()){
            return view();
        }else{
            $data['user'] = null;
            $data['status'] = 0;
            $data['msg'] = '注册失败';
            try{
                $user = new UserModel([
                    'name' => $request->param('name',''),
                    'password' => md5($request->param('password','123456')),
                    'nick' => $request->param('nick',''),
                    'address' => $request->param('address','')
                ]);
                $user->save();
                $data['user'] = $user;
                $data['status'] = 1;
                $data['msg'] = '注册成功！！！';
            }catch(exception $exceptions){
                $data['exception'] = $exceptions;
            }
           return json($data);
        }
    }


    public function user_exist($name = ''){
        $user = UserModel::where('name','=',$name)->limit(0,1)->find();
        $data['user'] = null;
        $data['status'] = 1;
        $data['msg'] = 'name可用|'.$name;
        $data['valid'] = true;
        if($user){
            $data['user'] = $user;
            $data['status'] = 0;
            $data['msg'] = 'name不可用|'.$name;
            $data['valid'] = false;
        }
        return json($data);
    }
}
